package com.syqc.utils

import android.app.ActivityManager
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.view.animation.AnimationUtils
import android.widget.ImageView
import androidx.core.net.toUri
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import com.syqc.comlib.utils.toast
import com.syqc.monitor.R
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketAddress


/** @Author Jasper @Time 2020/7/21 @Desc */
object ToolsUtil {
    /** 通过状态判断是否有定位 */
    fun isNoLocation(state: String): Boolean {
        return when (state) {
            "1", "5", "" -> true
            else -> false
        }
    }

    fun getPartByPath(name: String, path: String): MultipartBody.Part? {
        if (name.isEmpty() || path.isEmpty()) return null
        val bitmap: Bitmap? =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                PhotoUtil.compressImage(PhotoUtil.getBitmapFormUri(path.toUri()))
            } else {
                PhotoUtil.compressImage(PhotoUtil.getImage(path))
            }
        val body: RequestBody =
            PhotoUtil.bitmap2Bytes(bitmap).toRequestBody("multipart/form-data".toMediaTypeOrNull())
        return MultipartBody.Part.createFormData(name, "$name.jpg", body)
    }

    fun getPartByPath(key: String, name: String, path: String): MultipartBody.Part? {
        if (name.isEmpty() || path.isEmpty()) return null
        val bitmap: Bitmap? =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                PhotoUtil.compressImage(PhotoUtil.getBitmapFormUri(path.toUri()))
            } else {
                PhotoUtil.compressImage(PhotoUtil.getImage(path))
            }
        val body: RequestBody =
            PhotoUtil.bitmap2Bytes(bitmap).toRequestBody("multipart/form-data".toMediaTypeOrNull())
        try {
            return MultipartBody.Part.createFormData(key, "$name.jpg", body)
        } finally {
            // 释放资源
            bitmap?.recycle()
        }
    }

    fun getVideoPart(path: String?): MultipartBody.Part? {
        if (path.isNullOrEmpty()) return null
        val file = File(path)
        val requestBody = file.asRequestBody("video/*".toMediaTypeOrNull())
        return MultipartBody.Part.createFormData("files", file.name, requestBody)
    }

    /** 获取剪切板内容 */
    fun getClipboardStr(context: Context): String {
        val plaster = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        if (!plaster.hasPrimaryClip()) return ""
        val clipData = plaster.primaryClip ?: return ""
        val count = clipData.itemCount
        var resultString = ""
        for (index in 0 until count) {
            val item = clipData.getItemAt(index)
            val str = item.coerceToText(context)
            resultString += str
        }
        return resultString
    }

    private var lastClickTime: Long = 0

    @Synchronized
    fun isFastClick(): Boolean {
        val time = System.currentTimeMillis()
        if (time - lastClickTime < 500) {
            return true
        }
        lastClickTime = time
        return false
    }

    fun formatTo2F(float: Any): String {
        return String.format("%.2f", float)
    }

    fun initPushPlayer() {
        PlayerFactory.setPlayManager(IjkPlayerManager::class.java)
    }
//
//    /** 是否显示报警 */
//    fun setPush() {
//        val isAlarm = CacheMMKV.decodeBoolean(Keys.SETTING_ALARM)
//        if (isAlarm) {
//            PushUtil.initPush()
//            PushUtil.onPush()
//        } else {
//            PushUtil.initPush()
//            PushUtil.offPush()
//        }
//    }

    /**
     * 判断app是否处于前台
     *
     * @return
     */
    fun isAppOnForeground(context: Context): Boolean {
        val activityManager =
            context.applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val packageName: String = context.packageName

        /** 获取Android设备中所有正在运行的App */
        val appProcesses = activityManager.runningAppProcesses ?: return false
        for (appProcess in appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true
            }
        }
        return false
    }

    /** 格式话数字精度 */
    fun formitNumber(precision: String, num: Double): String {
        return String.format("%.${precision}f", num)
    }

    /** 格式话数字精度 */
    fun formitNumberD(precision: Any, num: Float): Float {
        return String.format("%.${precision}f", num).toFloat()
    }

    /** 格式话数字精度 */
    fun formitNumberD(precision: Any, num: Double): Double {
        return String.format("%.${precision}f", num).toDouble()
    }

    /** 通过状态返回颜色 */
    fun stateColor(state: String) = when (state) {
        //欠费
        "2", "6" -> "#EC9000"
        //无效定位
        "13" -> "#7F00D9"
        //报警
        "4", "8", "11", "12" -> "#FF0000"
        //离线
        "1", "3" -> "#999999"
        //其他
        else -> "#2461f7"
    }

    /** 通过状态返回背景 */
    fun getListBgRes(state: String): Int {
        return when (state) {
            "2", "6" -> R.drawable.bg_list_arreras
            "1", "3", "4" -> R.drawable.bg_list_offline
            else -> R.drawable.bg_list_normal
        }
    }
//

    private var isLoad = false

    fun startAmin(img: ImageView) {
        if (!isLoad) {
            val loadAnimation = AnimationUtils.loadAnimation(img.context, R.anim.anim_rotate)
            loadAnimation.fillAfter = false
            img.startAnimation(loadAnimation)
            isLoad = true
        }
    }

    fun stopAmin(img: ImageView) {
        isLoad = false
        img.clearAnimation()
    }

    fun startAminDown(img: ImageView) {
        if (!isLoad) {
            val loadAnimation = AnimationUtils.loadAnimation(img.context, R.anim.anim_down)
            loadAnimation.fillAfter = false
            img.startAnimation(loadAnimation)
            isLoad = true
        }
    }

    fun talkPhone(context: Context, phoneNum: String?) {
        if (phoneNum.isNullOrEmpty()) {
            R.string.desc_no_phone.toast(context)
        } else {
            //跳转到拨号界面，同时传递电话号码
            val dialIntent =
                Intent(Intent.ACTION_DIAL, Uri.parse("tel:${phoneNum}"))
            context.startActivity(dialIntent)
        }
    }

    /** 测试是否可以连接 */
    fun isReachableByTcp(host: String, port: Int): Boolean {
        val socket = Socket()
        return try {
            val socketAddress: SocketAddress = InetSocketAddress(host, port)
            socket.connect(socketAddress, 1000)
            true
        } catch (e: IOException) {
            false
        } finally {
            socket.close()
        }
    }


}